<template>
  <detail-frame :title="title">
    <el-form inline :label-width="120" label-suffix=":">
      <el-form-item class="form-item" label="创建人">
        {{ detail?.order.cuser }}
      </el-form-item>
      <el-form-item class="form-item" label="创建时间">
        {{ detail?.order.ctime }}
      </el-form-item>
      <el-form-item class="form-item" label="维修单号">
        {{ detail?.order.orderNumber }}
      </el-form-item>
      <el-form-item class="form-item" label="工单状态">
        {{ detail?.order.orderStatusName }}
      </el-form-item>
      <el-form-item class="form-item" label="客户名称">
        {{ detail?.order.customerName }}
      </el-form-item>
      <el-form-item class="form-item" label="站点名称">
        {{ detail?.order.siteName }}
      </el-form-item>
      <el-form-item class="form-item" label="联系人">
        {{ detail?.order.contactor }}
      </el-form-item>
      <el-form-item class="form-item" label="联系电话">
        {{ detail?.order.telephone }}
      </el-form-item>
      <el-form-item class="form-item-line" label="联系地址">
        {{ detail?.order.address }}
      </el-form-item>
      <el-form-item class="form-item" label="接收快递日期">
        {{ detail?.order.receiveDate.replace("00:00:00", "") }}
      </el-form-item>
      <el-form-item class="form-item" label="接收快递单号">
        {{ detail?.order.receiveNumber }}
      </el-form-item>
      <el-form-item class="form-item-line" label="备注">
        {{ detail?.order.comment || '' }}
      </el-form-item>
      <el-form-item class="form-item-line" label="附件">
        <file-gallary readonly :file-list="detail?.fileList || []"></file-gallary>
      </el-form-item>
    </el-form>
    <detail-list-frame title="产品清单" inner-control :columns="columns" :table-data="tableData" :total="tableData.length"
      :show-operations="true">
      <template #buttons>
        <el-button type="primary" size="small" @click="oneKeyPriceVisible = true">一键报价</el-button>
        <el-dialog :model-value="oneKeyPriceVisible" title="一键报价" lock-scroll :show-close="false" width="500"
          :close-on-click-modal="false">
          <zw-date-picker v-model="quoteDate"></zw-date-picker>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="onOneKeyPriceSubmit">提交</el-button>
              <el-button @click="oneKeyPriceVisible = false">关闭</el-button>
            </div>
          </template>
        </el-dialog>
      </template>
      <template #operations="row">
        <el-button link type="primary" @click="onOpenProductDetail(row)">明细</el-button>
        <el-button link type="danger" v-auth="'DeleteOrderProduct'" @click="onDeleteProdcut(row)">删除</el-button>
      </template>
    </detail-list-frame>
    <template #buttons>
      <el-button v-auth="'UpdateAfterSaleOrderDetail'" type="primary" @click="onUpdate">编辑</el-button>
      <el-button v-if="canStop" v-auth="'StopOrder'" type="primary" @click="onInvalid">作废</el-button>
      <el-button v-if="canDelete" v-auth="'DeleteAfterSaleOrderDetail'" type="danger" @click="onDelete">删除</el-button>
    </template>
  </detail-frame>
</template>
<script lang="ts" setup>
import DetailFrame from '@/components/DetailFrame/DetailFrame.vue';
import DetailListFrame from '@/components/DetailFrame/DetailListFrame.vue';
import ZwDatePicker from '@/components/Form/ZwDatePicker.vue';
import ElConfirm from '@/components/ElConfirm';
import FileGallary from '@/components/Form/FileGallary.vue';
import type { ColumnType } from '@/components/types';
import emits, { EventEnum } from '@/plugins/emits';
import StoreManager from '@/plugins/storage';
import WinUtil, { WinNameRecord } from '@/plugins/window';
import { OrderStatusEnum, type OrderDetailDTO } from '@/server/afterSale/types';
import ApiTree from '@/server/api-tree';
import type { UserVO } from '@/server/user/types';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import DateUtil from '@/plugins/date';
const route = useRoute()
const title = ref<string>("")
const guid = ref<string>(route.query.guid?.toString() || "");
/** 明细 */
const detail = ref<OrderDetailDTO>();
const canEdit = ref(true);
const canDelete = ref(true);
const canStop = ref(true);
const user = ref<UserVO | null>(StoreManager.get<UserVO>("user"));
const getDetail = async () => {
  const { success, data } = await ApiTree.afterSaleOrder.detail(guid.value);
  if (success) {
    title.value = `售后维修订单明细【${data.order.orderNumber}】`
    detail.value = data;
    // 生成产品表格数据
    data.products.forEach(product => {
      const check = data.productChecks.find(x => x.orderId === product.orderId && x.productSn === product.productSn);
      const checkParts = data.productCheckPrices.filter(x => x.orderId === product.orderId && x.productSn === product.productSn);
      const repair = data.productRepairs.find(x => x.orderId === product.orderId && x.productSn === product.productSn);
      tableData.value.push({
        orderId: product.orderId,
        productName: product.productName,
        productSn: product.productSn,
        comment: product.comment || "",
        repairState: product.repairState,
        questionCheck: check?.questionCheck || "",
        cuser: check?.cuser || "",
        warranty: check?.warranty || "",
        productPartNameList: checkParts.map(x => x.productPartName).join(","),
        totalPrice: Math.round(checkParts.map(x => x.totalPrice).reduce((p, c) => ((p + c + Number.EPSILON) * 100 / 100), 0) * 100) / 100,
        workHourPrice: check?.workHourPrice || 0,
        payState: repair?.payState || "",
        returnDate: repair?.returnDate.replace("00:00:00", "") || "",
        returnNumber: repair?.returnNumber || ""
      })
    })
    // 当前用户是管理员或者是本人，且状态是新提交
    canDelete.value = canEdit.value = user.value?.role === "ADMIN" || (user.value?.guid === data.order.cuserId && data.order.orderStatus === OrderStatusEnum.SUBMITTED);
    canStop.value = user.value?.role === "ADMIN";
  }
}
/** 产品列表 */
const columns = ref<ColumnType[]>([
  { prop: "productName", colName: "产品名称", width: 160, fixed: "left" },
  { prop: "productSn", colName: "产品SN", width: 160, fixed: "left" },
  { prop: "comment", colName: "备注", width: 120 },
  { prop: "repairState", colName: "维修状态", width: 120 },
  { prop: "questionCheck", colName: "检测故障", width: 160 },
  { prop: "cuser", colName: "检测工程师", width: 100 },
  { prop: "warranty", colName: "质保状态", width: 100 },
  { prop: "productPartNameList", colName: "更换配件", width: 120 },
  { prop: "totalPrice", colName: "配件费总计", width: 120 },
  { prop: "workHourPrice", colName: "工时费", width: 120 },
  { prop: "payState", colName: "支付状态", width: 120 },
  { prop: "returnDate", colName: "快递返回日期", width: 130 },
  { prop: "returnNumber", colName: "快递返回单号", width: 130 },
])
type TableData = {
  orderId: string,
  productName: string, productSn: string, comment: string, repairState: string, questionCheck: string, cuser: string, warranty: string,
  productPartNameList: string, totalPrice: number, workHourPrice: number, payState: string, returnDate: string, returnNumber: string
};
const tableData = ref<TableData[]>([]);
/** 编辑 */

const onUpdate = () => {
  WinUtil.open("/afterSale/order/update?guid=" + guid.value, WinNameRecord.ORDER_UPDATE, guid.value);
}
/** 删除 */
const onDelete = () => {
  ElConfirm(`确定要删除工单吗？`).then(async () => {
    const { success, msg } = await ApiTree.afterSaleOrder.delete(guid.value);
    if (success) {
      ElMessage.success(msg);
      setTimeout(() => {
        window.close();
      }, 200);
    }
  }).catch();
}
/** 作废 */
const onInvalid = () => {
  ElConfirm(`确定要作废工单吗，一旦作废，将无法进行任何操作！`).then(async () => {
    const { success, msg } = await ApiTree.afterSaleOrder.invalid(guid.value);
    if (success) {
      ElMessage.success(msg);
      setTimeout(() => {
        window.close();
      }, 200);
    }
  }).catch();
}
/** 打开产品明细页 */
const onOpenProductDetail = (row: { value: TableData }) => {
  const { orderId, productSn } = row.value;
  WinUtil.open(`/afterSale/order/${orderId}/detail?sn=` + productSn, WinNameRecord.ORDER_PRODUCT_DETAIL, orderId, productSn)
}
const onDeleteProdcut = (row: { value: TableData }) => {
  ElConfirm(`确定要删除产品：【${row.value.productSn}】吗？`).then(async () => {
    const { success, msg } = await ApiTree.afterSaleOrder.deleteProduct(row.value.orderId, row.value.productSn);
    if (success) {
      ElMessage.success(msg);
      WinUtil.reload();
    }
  }).catch();
}
/** 监听一下刷新事件 */
emits.on(EventEnum.DETAIL_RELOAD, data => {
  if (data === guid.value) {
    WinUtil.reload();
  }
})
/** 一键报价 */
const oneKeyPriceVisible = ref(false)
const quoteDate = ref(DateUtil.now());
const onOneKeyPriceSubmit = () => {
  ElConfirm(`确定提交一键报价吗？所有产品将都更新为已报价，报价日期为${DateUtil.resolve(quoteDate.value, true)}！`).then(async () => {
    const { success, msg } = await ApiTree.afterSaleOrder.oneKeyPrice(guid.value, quoteDate.value);
    if (success) {
      ElMessage.success(msg);
      WinUtil.reload();
    }
  }).catch();
}
onMounted(() => {
  if (!guid.value) {
    ElMessage.error("缺少参数！");
    return;
  }
  getDetail();
})
</script>
<style lang="scss" scope></style>
